package struts.annotation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.plaf.synth.SynthScrollBarUI;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import struts.utility.AnnotationBean;
import struts.utility.ClasspathPackageScanner;
import sun.awt.SunHints.Value;

/**
 * 扫描指定包下的类的注解，存储到Bean
 * @author Administrator
 *
 */
public class ParseAnnotation {

	public ParseAnnotation() {
	}
	
	//测试
	public static void main(String[] args){
		try {
			
			Map<String, AnnotationBean> map = parseAnnotation("com.xsoft");
			
			Set<String> keySet = map.keySet();
			for(Iterator<String> it = keySet.iterator(); it.hasNext();){
				String actionPath = it.next();
				System.out.println(actionPath);
				System.out.println(map.get(actionPath));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static  Map<String, AnnotationBean> parseAnnotation(String packageName) throws Exception{
		List<String> classNames=ClasspathPackageScanner.getClassNames(packageName);
		List<AnnotationBean> annotationBeans=new ArrayList<AnnotationBean>();
		for(String className:classNames){
			Class clazz=Class.forName(className);
			
			if(clazz.isAnnotationPresent(ActionMapping.class)){
				ActionMapping actionMapping=(ActionMapping) clazz.getAnnotation(ActionMapping.class);
				System.out.println(actionMapping.name()+"--"+actionMapping.type()+"--"+actionMapping.path()+"--"+actionMapping.success()+"--"+actionMapping.fail());
			
					AnnotationBean annotationBeanBean = new AnnotationBean();
					annotationBeanBean.setActionName(actionMapping.name());
					annotationBeanBean.setActionPath(actionMapping.path());
					annotationBeanBean.setActionType(actionMapping.type());
					Map actionForwardMap=new HashMap<String,String>();
					actionForwardMap.put("success", actionMapping.success());
					actionForwardMap.put("fail", actionMapping.fail());
					annotationBeanBean.setActionForwardMap(actionForwardMap);
					
					annotationBeans.add(annotationBeanBean);
			}
		}
		
		for(String className:classNames){
			Class clazz=Class.forName(className);
			
			if(clazz.isAnnotationPresent(FormBean.class)){
				FormBean formBean = (FormBean) clazz.getAnnotation(FormBean.class);
				System.out.println(formBean.name()+"--"+formBean.type());
				
				for(AnnotationBean annotationBean:annotationBeans){
					if(annotationBean.getActionName().equals(formBean.name())){
						annotationBean.setFormBeanName(formBean.name());
						annotationBean.setFormBeanType(formBean.type());
					}
				}
			}
		}
		
		Map<String, AnnotationBean> map = new HashMap<String, AnnotationBean>();
		for(AnnotationBean annotationBean:annotationBeans){
			map.put(annotationBean.getActionPath(), annotationBean);
		}
		
		return map;
	}
}
